package com.friend.integration.job;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.friend.domain.question.Question;
import com.friend.domain.question.es.QuestionES;
import com.friend.integration.elasticsearch.QuestionRepository;
import com.friend.mapper.question.QuestionMapper;
import com.friend.util.QuestionConverter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 题目同步定时任务
 * 定时检查数据库变更并同步到ES
 */
@Component
@Slf4j
public class QuestionSyncJob {
    
    @Autowired
    private QuestionMapper questionMapper;
    
    @Autowired
    private QuestionRepository questionRepository;
    
    /**
     * 增量同步 - 每5分钟执行一次
     * 只同步最近5分钟内变更的题目
     * 使用QuestionConverter确保LocalDateTime正确转换
     */
    @Scheduled(fixedRate = 300000) // 5分钟
    public void incrementalSync() {
        try {
            // 查询最近5分钟内变更的题目
            LocalDateTime fiveMinutesAgo = LocalDateTime.now().minusMinutes(5);
            LambdaQueryWrapper<Question> wrapper = new LambdaQueryWrapper<Question>()
                    .ge(Question::getUpdateTime, fiveMinutesAgo)
                    .or()
                    .ge(Question::getCreateTime, fiveMinutesAgo);
            
            List<Question> changedQuestions = questionMapper.selectList(wrapper);
            
            if (changedQuestions.isEmpty()) {
                return;
            }
            
            // 同步到ES - 使用专门的转换工具
            for (Question question : changedQuestions) {
                try {
                    QuestionES questionES = QuestionConverter.toQuestionES(question);
                    questionRepository.save(questionES);
                } catch (Exception e) {
                    log.error("同步题目到ES失败 - questionId: {}, error: {}", 
                            question.getQuestionId(), e.getMessage());
                }
            }
            
            log.info("增量同步完成，共同步 {} 个题目", changedQuestions.size());
            
        } catch (Exception e) {
            log.error("增量同步失败: {}", e.getMessage(), e);
        }
    }
    
    /**
     * 全量同步 - 每天凌晨2点执行一次
     * 确保ES和数据库数据一致性
     */
    @Scheduled(cron = "0 0 2 * * ?")
    public void fullSync() {
        try {
            List<Question> allQuestions = questionMapper.selectList(new LambdaQueryWrapper<Question>());
            
            if (allQuestions.isEmpty()) {
                log.warn("没有找到题目数据");
                return;
            }
            
            // 批量同步到ES - 使用专门的转换工具
            for (Question question : allQuestions) {
                try {
                    QuestionES questionES = QuestionConverter.toQuestionES(question);
                    questionRepository.save(questionES);
                } catch (Exception e) {
                    log.error("同步题目到ES失败 - questionId: {}, error: {}", 
                            question.getQuestionId(), e.getMessage());
                }
            }
            
            log.info("全量同步完成，共同步 {} 个题目", allQuestions.size());
            
        } catch (Exception e) {
            log.error("全量同步失败: {}", e.getMessage(), e);
        }
    }
}
